package mornd.tomcat.test1;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: mornd
 * @dateTime: 2023/5/9 - 15:05
 */

@Controller
public class Controller1 {

    @RequestMapping("/test")
    public ModelAndView test() {
        int i = 1/0;
        return null;
    }

    /**
     * tomcat 出现异常后，会将异常对象存进 request 作用域，key为 javax.servlet.error.exception
     * @return
     */
    @ResponseBody
    //@RequestMapping("/error")
    public Map error(HttpServletRequest request) {
        Throwable t = (Exception) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
        return new HashMap<String, Object>() {{
            put("error", t.getMessage());
        }};
    }
}
